<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="类型" prop="type" label-width="100px">
              <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
                <el-option v-for="dict in busi_store_balance_change_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <!-- <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:storeBalanceChange:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template> -->

      <el-table v-loading="loading" :data="storeBalanceChangeList" @selection-change="handleSelectionChange">
        <el-table-column label="类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="busi_store_balance_change_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="内容" align="center" prop="content" /> -->
        <el-table-column label="时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="历史" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip v-if="scope.row.type === 2" content="查看问诊记录" placement="top">
              <el-button
                v-hasPermi="['business:storeBalanceChange:query']"
                link
                type="success"
                icon="ChatDotRound"
                @click="handleFindOneChatList(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tag v-if="scope.row.type === 1" type="success">+{{ parseInt(scope.row.balanceChange) }}</el-tag>
            <!-- <el-tooltip content="删除" placement="top">
              <el-button
                v-hasPermi="['business:storeBalanceChange:remove']"
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
              ></el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改诊所余额变动对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="680px" append-to-body>
      <el-form ref="storeBalanceChangeFormRef" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="变动编号" prop="changeNo">
          <el-input v-model="form.changeNo" placeholder="请输入变动编号" readonly />
        </el-form-item>
        <el-form-item label="诊所ID" prop="storeId">
          <el-input v-model="form.storeId" placeholder="请输入诊所ID" readonly />
        </el-form-item>
        <el-form-item label="诊所名称" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入诊所名称" readonly />
        </el-form-item>
        <!-- <el-form-item label="系统用户ID" prop="sysUserId">
          <el-input v-model="form.sysUserId" placeholder="请输入系统用户ID" />
        </el-form-item> -->
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type" disabled>
            <el-radio v-for="dict in busi_store_balance_change_type" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="变动前次数" prop="before">
          <el-input v-model="form.balanceBefore" placeholder="请输入变动前次数" readonly />
        </el-form-item>
        <el-form-item label="本次变动" prop="change">
          <el-input v-model="form.balanceChange" placeholder="请输入变动次数" readonly />
        </el-form-item>
        <el-form-item label="变动后次数" prop="after">
          <el-input v-model="form.balanceAfter" placeholder="请输入变动后次数" readonly />
        </el-form-item>
        <el-form-item label="变动内容">
          <el-input v-model="form.content" placeholder="请输入变动内容" readonly />
          <!-- <editor v-model="form.content" :min-height="192" /> -->
        </el-form-item>
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button> -->
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改诊所余额变动对话框 -->
    <el-dialog v-model="dialogOneChatList.visible" :title="dialogOneChatList.title" width="680px" append-to-body>
      <el-timeline>
        <el-timeline-item
          v-for="chat in oneChatList"
          :key="chat.id"
          :timestamp="chat.timeStr"
          placement="top"
          :type="chat.obj === 'Human' ? 'success' : 'primary'"
        >
          <el-card class="box-card">
            <h4>
              <el-tag v-if="chat.obj === 'Human'" type="success">{{ currentStoreName ? currentStoreName : '诊所医生' }}</el-tag>
              <el-tag v-if="chat.obj === 'AI'" type="primary">医小智</el-tag>
            </h4>
            <div v-html="marked(chat.title)"></div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogOneChatList.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="StoreBalanceChange" lang="ts">
import { listStoreBalanceChange, getStoreBalanceChange, findOneChatList } from '@/api/business/storeBalanceChange';
import { StoreBalanceChangeVO, StoreBalanceChangeQuery, StoreBalanceChangeForm } from '@/api/business/storeBalanceChange/types';
import { error } from 'console';
import { marked } from 'marked';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { busi_store_balance_change_type } = toRefs<any>(proxy?.useDict('busi_store_balance_change_type'));

const storeBalanceChangeList = ref<StoreBalanceChangeVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const storeBalanceChangeFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialogOneChatList = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: StoreBalanceChangeForm = {
  id: undefined,
  changeNo: undefined,
  storeId: undefined,
  sysUserId: undefined,
  type: undefined,
  balanceBefore: undefined,
  balanceChange: undefined,
  balanceAfter: undefined,
  content: undefined,
  remark: undefined,
  storeName: undefined
};
const data = reactive<PageData<StoreBalanceChangeForm, StoreBalanceChangeQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    changeNo: undefined,
    storeId: undefined,
    sysUserId: undefined,
    type: undefined,
    balanceBefore: undefined,
    balanceChange: undefined,
    balanceAfter: undefined,
    storeName: undefined,
    params: {}
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询诊所余额变动列表 */
const getList = async () => {
  loading.value = true;
  const res = await listStoreBalanceChange(queryParams.value);
  storeBalanceChangeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  storeBalanceChangeFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: StoreBalanceChangeVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加诊所次数变动';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: StoreBalanceChangeVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getStoreBalanceChange(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '查看诊所次数变动';
};

const currentStoreName = ref('');
const oneChatList = ref([]);

const handleFindOneChatList = async (row?: StoreBalanceChangeVO) => {
  currentStoreName.value = '';
  const _chatId = row?.remark;
  if (_chatId) {
    const res = await findOneChatList({ chatId: _chatId });
    currentStoreName.value = row.storeName;
    oneChatList.value = [];
    Object.assign(oneChatList.value, res.data);
    dialogOneChatList.visible = true;
    dialogOneChatList.title = '查看问诊记录';
  } else {
    proxy?.$modal.msgError('问诊记录不存在');
  }
};

/** 提交按钮 */
// const submitForm = () => {
//   storeBalanceChangeFormRef.value?.validate(async (valid: boolean) => {
//     if (valid) {
//       buttonLoading.value = true;
//       if (form.value.id) {
//         await updateStoreBalanceChange(form.value).finally(() => (buttonLoading.value = false));
//       } else {
//         await addStoreBalanceChange(form.value).finally(() => (buttonLoading.value = false));
//       }
//       proxy?.$modal.msgSuccess('操作成功');
//       dialog.visible = false;
//       await getList();
//     }
//   });
// };

/** 删除按钮操作 */
// const handleDelete = async (row?: StoreBalanceChangeVO) => {
//   const _ids = row?.id || ids.value;
//   await proxy?.$modal.confirm('是否确认删除诊所余额变动编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
//   await delStoreBalanceChange(_ids);
//   proxy?.$modal.msgSuccess('删除成功');
//   await getList();
// };

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/storeBalanceChange/export',
    {
      ...queryParams.value
    },
    `storeBalanceChange_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
